/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package makao;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JEditorPane;
import javax.swing.JTextPane;
import shared.MakaoPackage;
import sun.nio.ch.SocketAdaptor;

/**
 *
 * @author gekon
 */
public class Connection extends Thread
{

    private MakaoView makaoView = null;
    private InetAddress serverAddress = null;
    private String login = null;
    private int serverPort;
    private Socket connection = null;
    private SocketAddress socketAddress = null;
    private InputStream input = null;
    private OutputStream output = null;
    private ObjectOutputStream objectOutputStream = null;
    private ObjectInputStream objectInputStream = null;
    private Boolean connectionFlag = true;
    private Boolean loginFlag = false;
    private MakaoPackage makaoPackageIn = null;
    private MakaoPackage makaoPackageOut = null;
    private ArrayList<String> loginArray = new ArrayList<String>();
    private JEditorPane logPane;

    public Connection(String serverAddress, int serverPort, String login, JEditorPane logPane, MakaoView makaoView) throws IOException
    {
        try
        {
            this.serverAddress = InetAddress.getByName(serverAddress);
            this.serverPort = serverPort;
            this.login = login;
            this.logPane = logPane;
            this.makaoView = makaoView;

            socketAddress = new InetSocketAddress(serverAddress, serverPort);
            connection = new Socket();
            connection.connect(socketAddress, 3000);
            logPane.setText(logPane.getText() + "Połączono się poprawnie z serwerem.\n");

            input = connection.getInputStream();
            output = connection.getOutputStream();
            objectOutputStream = new ObjectOutputStream(output);
            objectInputStream = new ObjectInputStream(input);

            loginArray.add(login);
            this.start();
            sendDemandLogOn();
        } catch (UnknownHostException ex)
        {
            logPane.setText(logPane.getText() + "BŁĄD LOGOWANIA!!!\nPrawdopodobnie zły adres serwera lub problem z połączeniem sieciowym\n");
            logPane.setVisible(true);
        }
    }

    public Socket getSocket()
    {
        return connection;
    }

    @Override
    public void run()
    {


        while (connectionFlag)
        {
            {
                try
                {
                    makaoPackageIn = (MakaoPackage) objectInputStream.readObject();

                    if (makaoPackageIn != null)
                    {
                        if (loginFlag == false)
                        {
                            if ((makaoPackageIn.getCommand() == MakaoPackage.LOGIN_RESPONSE)
                                    && (makaoPackageIn.getValues().get(0).equals("OK")))
                            {
                                loginFlag = true;
                                addLog("Zalogowano poprawnie!");
                            } else
                            {
                                addLog("Wystąpił błąd przy próbie logowania. Przyczyna: " + makaoPackageIn.getValues().get(1));
                                disconnect();
                            }
                        } else
                        {

                            if (makaoPackageIn.getCommand() == MakaoPackage.GAME_INFO)
                            {
                                makaoView.getPlayerData().clearThrownCardsArray();
                                makaoView.getPlayerData().setGameStart(true);
                                makaoView.getPlayerData().setGameInfo(makaoPackageIn.getGameInfo());
                                makaoView.getPlayerData().setMyCards(makaoPackageIn.getMyCards());
                            }
                            if (makaoPackageIn.getCommand() == MakaoPackage.GAME_FINISHED)
                            {
                                addLog("....Koniec gry....\nWygrał gracz: " + makaoPackageIn.getValues().get(0).toUpperCase());
                                makaoView.getCardsPanel().setEnabled(false);
                                makaoView.getTablePanel().setEnabled(false);
                                makaoView.getPlayerData().clearPlayerDataToNextgame();
                            }
                            if (makaoPackageIn.getCommand() == MakaoPackage.ERROR)
                            {
                                addLog("Wystąpił błąd. Przyczyna: " + makaoPackageIn.getValues().get(0) + "\n");
                                makaoView.getPlayerData().rollbackThrownCards();
                            }
                        }
                    }

                } catch (ClassNotFoundException ex)
                {
                    addLog("Serwer wyłączony");
                    disconnect();
                } catch (IOException ex)
                {
                    addLog("Serwer wyłączony");
                    disconnect();
                }
            }
        }

    }

    private void addLog(String text)
    {
        logPane.setText(logPane.getText() + text + "\n");
    }

    public ObjectOutputStream getObjectOutputStream()
    {
        return objectOutputStream;
    }

    public void logout()
    {
        connectionFlag = false;
        disconnect();
    }

    public void sendDemandLogOn()
    {
        try
        {
            makaoPackageOut = new MakaoPackage(MakaoPackage.LOGIN, loginArray);
            objectOutputStream.writeObject(makaoPackageOut);
            objectOutputStream.flush();
        } catch (IOException ex)
        {
            addLog("Rozłączony serwer. Powtórz proces logowania1");
            disconnect();
        }
    }

    public void disconnect()
    {
        try
        {
            if (objectInputStream != null)
            {
                objectInputStream.close();
            }
            
            if (objectInputStream != null)
            {
                objectOutputStream.close();
            }
            input.close();
            output.close();
            if (connection != null)
            {
                connection.close();
                connection = null;
            }
            connectionFlag = false;
            makaoView.getPlayerData().clearPlayerData();
            makaoView.clearFinalConnection();
        } catch (IOException ex)
        {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getLogin()
    {
        return login;
    }
}
